// pages/order/order.js
import {getorderapi,balanceapi,payorderapi,wechatpayapi,wechatpaylxapi} from "../../utils/api"
import utils from "../../utils/util"
// 轮询定义的时间变量
var time =null  
Page({

    /**
     * 页面的初始数据
     */
    
    data: {
    showaddress: false,//选择地址是否显示
    addressid:0,//选中地址的索引
    showticket:false,//优惠劵是否显示
    ticketid:-1,//选中优惠劵的索引
    address:{},//地址数据
    shopname:{},//商店数据
    goods:{},//商品数据
    ticket:{},//优惠劵数据
    total:{},//总价数据
    wechatoff:true,
    // 选择优惠劵传的参数
    order:{
        goods_sku_id:"",
        goods_num:"",
        coupon_id:""
    },
    // 提交订单传的参数
    order1:{
        collapse_shipping_address_id:"",
        goods_sku_id:"",
        goods_num:"",
        order_message:"",
        coupon_id:""
    },
    paydata:false,//支付
    order_id:""
    },
    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        // console.log(JSON.parse(options.order));
        this.data.order = JSON.parse(options.order)
        this.data.order1.goods_sku_id= JSON.parse(options.order).goods_sku_id
        this.data.order1.goods_num= JSON.parse(options.order).goods_num
        this.setData({
            order:this.data.order,
            order1:this.data.order1
        })
        const res = await getorderapi(JSON.parse(options.order))
        
        if(res.data.code == 200){
            wx.hideLoading()
            console.log(res.data.data);
            var arr = res.data.data.coupon
            // 优惠劵数据处理
            for (let i = 0; i < arr.length; i++) {
                arr[i].coupon_floor = parseInt(arr[i].coupon_floor)
                arr[i].coupon_price = parseInt(arr[i].coupon_price)
                arr[i].coupon_start = utils.formatTime(new Date(arr[i].coupon_start * 1000))
                arr[i].coupon_stop = utils.formatTime(new Date(arr[i].coupon_stop * 1000))
            }
            //数据进来的第一次的地址id赋值
            if(res.data.data.collapse_shipping_address.length!=0){
                console.log(0);
                this.data.order1.collapse_shipping_address_id = res.data.data.collapse_shipping_address[0].id
            }
            this.setData({
                address:res.data.data.collapse_shipping_address,
                shopname:res.data.data.mch,
                goods:res.data.data.goods,
                ticket:arr,
                total:res.data.data.total,
                order1:this.data.order1
            })
        }else{
            this.setData({
                address:{},
                shopname:{},
                goods:{},
                ticket:{},
                total:{}
            })
        }
        // console.log(this.data.order1);
    },
    // 地址的选择
    addressbtn(e){
        this.data.order1.collapse_shipping_address_id= e.currentTarget.dataset.id
        this.setData({
            addressid:e.currentTarget.dataset.index,
            showaddress: false,
            order1:this.data.order1
        })
    },
    // 优惠劵选择
   async ticketbtn(e){
        console.log(e.currentTarget.dataset.index,e.currentTarget.dataset.id);
        this.data.order.coupon_id = e.currentTarget.dataset.id
        this.setData({
            ticketid:e.currentTarget.dataset.index,
            order:this.data.order
        })
        console.log(this.data.order1);
       const res = await getorderapi(this.data.order)
       if(res.data.code == 200){
        wx.hideLoading()
        this.data.order1.coupon_id = e.currentTarget.dataset.id
        this.setData({
            total:res.data.data.total,
            showticket: false,
            order1:this.data.order1
        })
        }else if(res.data.code ==0){
            wx.hideLoading()
            utils.wxshowtoast("优惠劵不可用")
            this.setData({
                showticket: false
            })
        }else{
            wx.hideLoading()
            this.setData({
                total:{},
                showticket: false
            })
        }
    },
    // 提交订单
    async submit(){
        console.log(this.data.order1);
        if(this.data.order1.collapse_shipping_address_id ==""){
            utils.wxshowtoast("请添加地址")
            return
        }
        const res =await balanceapi(this.data.order1)
        if(res.data.code==200){
            wx.hideLoading()
            console.log(res.data.data);
            this.setData({
                paydata:true,
                order_id:res.data.data.order_id
            })
        }else{
            wx.hideLoading()
            utils.wxshowtoast("结算失败")
        }
    },
     // 支付轮询函数
     async _wxchatlxfn(data){
        const res =await wechatpaylxapi(data)
        if (res.data.code==200) {
            // 成功
            console.log(res.data);
            clearInterval(time)
            utils.wxshowtoast(res.data.msg)
            wx.reLaunch({
                url: '/pages/me/me',
              }) 
        } else if(res.data.code==201){
            // 已经成功了
            clearInterval(time)
            utils.wxshowtoast(res.data.msg)
            wx.reLaunch({
                url: '/pages/me/me',
              }) 
        }
    },
    // 微信支付
    async wechatpsy(){
        var that = this
        if(this.data.wechatoff){
            that.setData({
                wechatoff:false
            })
            utils.showLoading("正在提交支付...")
            const res = await wechatpayapi({
                pay_type:2,
                user_order_id:this.data.order_id,
                pay_money:this.data.num*100
            })
            wx.hideLoading({})
            if (res.data.code==200) {
               var pay_sn= res.data.data.pay_sn
               wx.requestOrderPayment({
                timeStamp: res.data.data.timeStamp,
                nonceStr: res.data.data.nonceStr,
                package: res.data.data.package,
                signType:res.data.data.signType,
                paySign: res.data.data.sign || res.data.data.paySign,
                success (res) {
                that.setData({
                    wechatoff:true
                })
                //  轮询支付结果
                time=setInterval(()=>{
                    that._wxchatlxfn({pay_sn:pay_sn})
                },1000)
                },
                fail (ret) {
                that.setData({
                    wechatoff:true
                })
                if (ret.errMsg === 'requestOrderPayment:fail cancel') {
                        utils.wxshowtoast('用户取消支付')
                    }
                }
                })
            } else {
                utils.wxshowtoast(res.data.msg)
                that.setData({
                    wechatoff:true
                })
            }
       }else{
        utils.wxshowtoast('用户已提交支付')
       }
    },
    // 支付
    async balancepay(){
    console.log(this.data.order_id);
    const res = await payorderapi({order_id:this.data.order_id})
    if(res.data.code == 400){
        wx.hideLoading()
        utils.wxshowtoast("余额不足，请充值")
        wx.redirectTo({
        url: '/pages/medetail/balance/balance',
        })
    }else if(res.data.code ==200){
        wx.hideLoading()
        utils.wxshowtoast("支付成功")
        wx.reLaunch({
          url: '/pages/me/me',
        }) 
    }else{
        wx.hideLoading()
        utils.wxshowtoast(res.data.msg)
    }
     console.log(res.data);
    },
    addressurl(){
       wx.redirectTo({
         url: '/pages/medetail/address/address',
       })
    },
    
    // 关闭支付
    Closepay(){
        this.setData({
            paydata:false
        })
    },
    // 买家留言
    message(e){
        this.data.order1.order_message = e.detail.value
        this.setData({
            order1:this.data.order1
        })
    },
    // 收货地址
    showaddress() {
    this.setData({ showaddress: true });
    },
    Closeaddress() {
    this.setData({ showaddress: false });
    },
    // 优惠劵
    showticket() {
    this.setData({ showticket: true });
    },
    Closeticket() {
    this.setData({ showticket: false });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.onLoad()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})